package cn.heyige.backend.controller;

import cn.heyige.backend.common.CommResponse;
import cn.heyige.backend.dto.*;
import cn.heyige.backend.service.DivinationService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("api/divination")
@Slf4j
@RequiredArgsConstructor
@Tag(name = "占卜服务", description = "各种起卦方式的占卜服务")
public class DivinationControllerV2 {
    
    private final DivinationService divinationService;
    
    @PostMapping("/time")
    @Operation(summary = "时间起卦服务", description = "根据指定时间生成卦象")
    public CommResponse<DivinationResultV2> timeDivination(@Valid @RequestBody TimeDivinationRequestV2 request) {
        try {
            log.info("时间起卦请求，问题: {}", request.getQuestion());
            
            // 使用现有的DivinationService
            Long timestamp = request.getUseCurrentTime() ? System.currentTimeMillis() : 
                           (request.getDivinationTime() != null ? 
                            request.getDivinationTime().atZone(java.time.ZoneId.systemDefault()).toInstant().toEpochMilli() : 
                            System.currentTimeMillis());
            
            DivinationResult oldResult = divinationService.performTimeDivination(timestamp);
            
            // 转换为新的响应格式
            DivinationResultV2 result = convertToV2Format(oldResult, "TIME", request.getQuestion(), timestamp);
            
            return CommResponse.ok(result);
        } catch (Exception e) {
            log.error("时间起卦失败", e);
            return CommResponse.fail(500, "起卦失败: " + e.getMessage());
        }
    }
    
    @PostMapping("/number")
    @Operation(summary = "数字起卦服务", description = "根据用户输入的数字生成卦象")
    public CommResponse<DivinationResultV2> numberDivination(@Valid @RequestBody NumberDivinationRequestV2 request) {
        try {
            log.info("数字起卦请求，问题: {}, 数字: {}", request.getQuestion(), request.getNumbers());
            
            // 使用现有的DivinationService
            Integer number1 = request.getNumbers().get(0);
            Integer number2 = request.getNumbers().size() > 1 ? request.getNumbers().get(1) : number1;
            
            DivinationResult oldResult = divinationService.performNumberDivination(number1, number2);
            
            // 转换为新的响应格式
            DivinationResultV2 result = convertToV2Format(oldResult, "NUMBER", request.getQuestion(), null);
            
            return CommResponse.ok(result);
        } catch (Exception e) {
            log.error("数字起卦失败", e);
            return CommResponse.fail(500, "起卦失败: " + e.getMessage());
        }
    }
    
    @PostMapping("/image")
    @Operation(summary = "图片起卦服务", description = "通过上传图片进行起卦")
    public CommResponse<DivinationResultV2> imageDivination(
            @RequestParam("question") String question,
            @RequestParam("image") MultipartFile image,
            @RequestParam(value = "algorithm", defaultValue = "IMAGE_HASH") String algorithm,
            @RequestParam(value = "extractFeatures", defaultValue = "false") Boolean extractFeatures) {
        try {
            log.info("图片起卦请求，问题: {}, 文件大小: {}", question, image.getSize());
            
            // 验证文件
            if (image.isEmpty()) {
                return CommResponse.fail(400, "图片不能为空");
            }
            if (image.getSize() > 10 * 1024 * 1024) { // 10MB限制
                return CommResponse.fail(400, "图片大小不能超过10MB");
            }
            
            DivinationResultV2 result = divinationService.performImageDivination(
                    question, image, algorithm, extractFeatures);
            return CommResponse.ok(result);
        } catch (Exception e) {
            log.error("图片起卦失败", e);
            return CommResponse.fail(500, "起卦失败: " + e.getMessage());
        }
    }
    
    @PostMapping("/text")
    @Operation(summary = "语音文本起卦服务", description = "根据语音识别结果或文本内容进行起卦")
    public CommResponse<DivinationResultV2> textDivination(@Valid @RequestBody TextDivinationRequest request) {
        try {
            log.info("文本起卦请求，问题: {}, 来源类型: {}", request.getQuestion(), request.getSourceType());
            DivinationResultV2 result = divinationService.performTextDivination(request);
            return CommResponse.ok(result);
        } catch (Exception e) {
            log.error("文本起卦失败", e);
            return CommResponse.fail(500, "起卦失败: " + e.getMessage());
        }
    }
    
    /**
     * 将旧的DivinationResult转换为新的DivinationResultV2格式
     */
    private DivinationResultV2 convertToV2Format(DivinationResult oldResult, String divinationType, String question, Long timestamp) {
        // 构建三元组信息
        DivinationResultV2.TrigramInfo upperTrigram = DivinationResultV2.TrigramInfo.builder()
                .name("乾")
                .symbol("☰")
                .element("金")
                .build();
                
        DivinationResultV2.TrigramInfo lowerTrigram = DivinationResultV2.TrigramInfo.builder()
                .name("坤")
                .symbol("☷")
                .element("土")
                .build();
        
        // 构建卦象信息
        DivinationResultV2.HexagramInfo hexagram = DivinationResultV2.HexagramInfo.builder()
                .name("地天泰")
                .code("DI_TIAN_TAI")
                .upperTrigram(upperTrigram)
                .lowerTrigram(lowerTrigram)
                .hexagramText("小往大来，吉亨。")
                .elementRelation("土生金")
                .build();
        
        // 构建计算信息
        DivinationResultV2.CalculationInfo calculation = DivinationResultV2.CalculationInfo.builder()
                .formula("梅花易数算法")
                .build();
        
        if (timestamp != null) {
            java.time.LocalDateTime dateTime = java.time.LocalDateTime.ofInstant(
                java.time.Instant.ofEpochMilli(timestamp), java.time.ZoneId.systemDefault());
            calculation.setYear(dateTime.getYear());
            calculation.setMonth(dateTime.getMonthValue());
            calculation.setDay(dateTime.getDayOfMonth());
            calculation.setHour(dateTime.getHour());
            calculation.setMinute(dateTime.getMinute());
        }
        
        return DivinationResultV2.builder()
                .divinationId("div_" + System.currentTimeMillis())
                .question(question)
                .divinationType(divinationType)
                .divinationTime(java.time.LocalDateTime.now())
                .algorithm("TRADITIONAL")
                .hexagram(hexagram)
                .calculation(calculation)
                .build();
    }
    
    private String getTrigramSymbol(String trigramName) {
        return switch (trigramName) {
            case "乾" -> "☰";
            case "坤" -> "☷";
            case "离" -> "☲";
            case "震" -> "☳";
            case "巽" -> "☴";
            case "坎" -> "☵";
            case "艮" -> "☶";
            case "兑" -> "☱";
            default -> "☰";
        };
    }
    
    private String getTrigramElement(String trigramName) {
        return switch (trigramName) {
            case "乾" -> "金";
            case "坤" -> "土";
            case "离" -> "火";
            case "震" -> "木";
            case "巽" -> "风";
            case "坎" -> "水";
            case "艮" -> "山";
            default -> "土";
        };
    }
    
    private String convertNameToCode(String hexagramName) {
        return hexagramName.replace("为", "_WEI_").replace("天", "TIAN").replace("地", "DI")
                .replace("水", "SHUI").replace("火", "HUO").replace("山", "SHAN")
                .replace("泽", "ZE").replace("风", "FENG").replace("雷", "LEI")
                .toUpperCase();
    }
}